<?php
/**
 * Create by PhpStorm.
 * User: guokunsheng
 * Date: 2024/10/23
 * Time: 16:10
 * @author Seunk <85152470@qq.com>
 */

namespace App\Models\CacheModel\ziwei;

use App\Models\Api\BaseCache;
use AstroTool\Cache\CacheManage;

/**
 * 紫微用户设置
 * Class Zl9ZiweiUserConfig.
 */
class Zl9ZiweiUserConfig extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl9_ziwei_user_config';

    protected $cacheModel = 'ziwei.config';

    /**
     * 保存数据
     * @param int $uid
     * @param array $config
     * @return int
     */
    public function SaveData(int $uid, array $config)
    {
        try
        {
            $nowTime = time();
            // 获取 用户紫薇 配置
            $configData = $this->getInfoById($uid);
            if ($configData)
            {   // 更新 紫薇 用户配置
                $this->where(['uid' => $uid])->update([
                    'config' => json_encode($config, JSON_UNESCAPED_UNICODE),
                    'update_time' => $nowTime,
                ]);
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();
                return $configData['id'];
            } else
            {   // 写入 紫薇 用户配置
                $data = [
                    'uid' => $uid,
                    'config' => json_encode($config, JSON_UNESCAPED_UNICODE),
                    'create_time' => $nowTime,
                    'update_time' => $nowTime,
                ];

                $id = $this->insertGetId($data);
                return (int)$id;
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            $data = $this->where(['uid' => ['in', $ids]])->column('id,uid,config,create_time,update_time', 'uid');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'create_time', 'update_time']);

            if (isset($itemData['config']))
            {
                $data[$index]['config'] = $itemData['config'] ? json_decode($itemData['config'], true) : [];
            }
        }

        return $data;
    }
}

